package leetcode.code0846;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

/**
 * 执行用时：41 ms, 在所有 Java 提交中击败了68.01%的用户
 *
 * 内存消耗：41.7 MB, 在所有 Java 提交中击败了5.27%的用户
 *
 * 通过测试用例：73 / 73
 */
public class Solution2 implements IDebug {

	public boolean isNStraightHand(int[] hand, int groupSize) {
//		Arrays.sort(hand);
		int len = hand.length;
		Map<Integer, Integer> map = new HashMap<>();
		Set<Integer> set = new HashSet<>();
		for (int i = 0; i < len; i++) {
			int num = hand[i];
			map.put(num, map.getOrDefault(num, 0) + 1);
			set.add(num);
		}
		List<Integer> list = new ArrayList<>(set);
		list.sort((a, b) -> a - b);
		int range = list.size();
		int[][] hash = new int[range][2];
		for (int i = 0; i < range; i++) {
			int num = list.get(i);
			hash[i][0] = num;
			hash[i][1] = map.get(num);
		}
		for (int i = 0; i < range;) {
			if (hash[i][1] == 0) {
				i++;
			} else {
				int sub = hash[i][1];
				int num = hash[i][0];
				int j = 0;
				int p = i + 1;
				while (j < groupSize - 1) {
					if ((p >= range) || (hash[p][0] != num + 1)) {
						return false;
					}
					num = hash[p][0];
					hash[p][1] -= sub;
					if (hash[p][1] < 0) {
						return false;
					}
					j++;
					p++;
				}
				i++;
			}
		}
		return true;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,6,2,3,4,7,8]"), 3));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,4,5]"), 4));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3(
				"[233722108,386144634,221638886,175028874,408337082,91410299,793763682,972910825,627251147,135020779]"),
				2));

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();

	}

}
